<template>
  <div class="MyNeed">
    <div class="MyNeed-title">
      <span>我的产品</span>
      <span class="add-btn">
        <a-button type="primary" @click="add" ghost>发布产品</a-button>
      </span>
    </div>
    <div class="mt-10 card-box">
      <a-form layout="inline" class="clearfix" :form="form" @submit="handleSubmit">
        <a-form-item label="关键字：">
          <a-input placeholder="请输入产品名称或者产品编号" v-decorator="['keyword']" />
        </a-form-item>
        <a-form-item label="产品状态：">
          <a-select style="width: 120px" @change="handleChange" v-decorator="['productStatus']" placeholder="请选择">
            <a-select-option value>请选择</a-select-option>
            <a-select-option v-for="item in reDemand" :value="item.key" :key="item.key">{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="审核状态：">
          <a-select style="width: 120px" @change="handleChange" v-decorator="['auditStatus']" placeholder="请选择">
            <a-select-option value>请选择</a-select-option>
            <a-select-option v-for="item in reExamine" :value="item.key" :key="item.key">{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="价格区间：">
          <a-input style="width: 120px" class="mr-10" v-decorator="['priceFrom']" />至
          <a-form-item>
            <a-input style="width: 120px" class="ml-10" v-decorator="['priceTo']" />
          </a-form-item>
        </a-form-item>
        <a-form-item label="供应上限：">
          <a-checkbox :checked="checkNick" @change="checkChange" v-decorator="['productIslimited']">不限</a-checkbox>
        </a-form-item>
        <a-form-item label="对接量：">
          <a-input style="width: 120px" class="mr-10" v-decorator="['messageCountFrom']" />至
          <a-form-item>
            <a-input style="width: 120px" class="ml-10" v-decorator="['messageCountTo']" />
          </a-form-item>
        </a-form-item>
        <a-form-item label="更新时间：">
          <a-range-picker @change="onChange" :placeholder="['开始日期', '结束日期']" v-decorator="['Data']">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
        </a-form-item>
        <div class="f-right mt-8">
          <a-button class="mr-8" style="color:#909399;" @click="clear">重置</a-button>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </div>
      </a-form>
    </div>

    <div class="action">
      <a-table :scroll="{ x: 1500}" :columns="columns" :data-source="ProduceList" :pagination="ipagination" :rowKey="record=>record.id">
        <div slot="productStatus" slot-scope="text,record" style="color: #0DA9B0;" v-if=" text == 1">
          已上架
          <span class="expire" v-show="record.durationDays<=14 && record.durationDays>=0 && record.durationDays!=null">
            即将下架
          </span>
        </div>
        <div slot="productStatus" slot-scope="text" v-else-if=" text == 2">未上架</div>
        <div slot="auditStatus" slot-scope="text" style="color: #E9284F;" v-if=" text == 1">审核中</div>
        <div slot="auditStatus" slot-scope="text" style="color: #0DA9B0;" v-else-if=" text == 2">已通过</div>
        <div slot="auditStatus" slot-scope="text" style="color: #EE6224;" v-else-if=" text == 3">未通过</div>
        <template slot="handle" slot-scope="text,recode">
          <a @click="showInforma(recode)">详情</a>
          <a-divider type="vertical" />
          <a @click="opera(recode)">编辑</a>
        </template>
        <a slot="name" slot-scope="text">{{ text }}</a>
        <span slot="action" slot-scope="text,record" class="operate-cls">
          <a @click="seeEdit(record)">查看详情</a>
          <a @click="seeReco(record)" v-if="record.auditStatus === 2">查看推送</a>
          <a v-show="record.ishandleEdit" @click="handleEdit(record)">编辑</a>
          <a v-show="record.isdeleEdit" @click="deleEdit(record)">删除</a>
          <a v-show="record.isshowInformation" @click="showInformation(record)">上架</a>
          <a v-show="record.isoperation" @click="operation(record)">下架</a>
          <a v-show="record.durationDays<=14 && record.durationDays>=0 && record.durationDays!=null && record.productStatus==1" @click="Renewal(record)">续期</a>
        </span>
      </a-table>
      <a-modal title="推荐企业" :visible="recoVis" :footer="null" @cancel="cancelRec">
      <a-table :rowKey="record=>record.entId" :columns="matchColumns" :data-source="recommCompanyInfo" bordered :pagination="false" :showHeader="false">
        <a slot="entName" slot-scope="text, record" target="_blank" title="点击可查看企业详情"
          :href="`${webHref}/aupply-chains-14-16203/entdetails?id=${record.entId}`">{{ text }}</a>
      </a-table>
    </a-modal>
    </div>
  </div>
</template>

<script>
import { getEntBaseInfo } from "@/apis/user/EntBaseInfo";
import { setIsSign } from "@/utils/auth"; //
import {
  GetproductList,
  Deleteproduct,
  updateProductStatus,
  addDurationTime,
  getProductEntPush
} from "@/apis/user/ProductInfo";
export default {
  data() {
    return {
      recoVis: false,
      userId: "",
      isSign: "",
      updateTimeFrom: "",
      updateTimeTo: "",
      checkNick: false,
      productIslimited: "",
      ProduceList: [],
      webHref: location.origin,
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          width: 80,
          align: "center",
          // customRender: (text, record, index) => `${index + 1}`, // 显示每一行的序
          customRender: (text, record, index) =>
            `${(this.ipagination.current - 1) * 10 + index + 1}`, // 显示每一行的序
        },
        {
          title: "产品名称",
          dataIndex: "productName",
          key: "productName",
          // ellipsis: true,
        },
        {
          title: "产品编号",
          dataIndex: "productNo",
          align: "center",
        },
        {
          title: "价格(元)",
          dataIndex: "isInterview",
          align: "center",
          customRender: function (text, recode) {
            if (text == 1) {
              return "面谈";
            } else if (text == 0 || text == null) {
              return recode.price + "元";
            }
          },
        },
        {
          title: "供应上限",
          dataIndex: "productIslimited",
          align: "center",
          customRender: function (text, recode) {
            if (text == 1) {
              return "不限";
            } else if (text == 0 || text == null) {
              return recode.productCeiling;
            }
          },
        },
        {
          title: "产品状态",
          dataIndex: "productStatus",
          align: "center",
          width: 150,
          scopedSlots: { customRender: "productStatus" },
          // customRender: function(text,recode) {
          //   if (text == 1) {
          //     return "已上架";
          //   } else if (text == 2) {
          //     return "未上架";
          //   }
          // }
        },

        {
          title: "对接量",
          align: "center",
          dataIndex: "messageCount",
        },
        {
          title: "审核状态",
          align: "center",
          dataIndex: "auditStatus",
          scopedSlots: { customRender: "auditStatus" },
          // customRender: function(text) {
          //   if (text == 1) {
          //     return "审核中";
          //   } else if (text == 2) {
          //     return "已通过";
          //   } else if (text == 3) {
          //     return "未通过";
          //   }
          // }
        },
        {
          title: "创建时间",
          align: "center",
          dataIndex: "createTime",
          //  ellipsis: true,
        },
        {
          title: "更新时间",
          align: "center",
          dataIndex: "updateTime",
          // ellipsis: true,
        },
        {
          title: "操作",
          dataIndex: "action",
          fixed: "right",
          align: "center",
          width: 200,
          scopedSlots: { customRender: "action" },
        },
      ],
      reDemand: [
        {
          label: "已上架",
          key: "1",
        },
        {
          label: "未上架",
          key: "2",
        },
      ],
      reExamine: [
        {
          label: "审核中",
          key: "1",
        },
        {
          label: "已通过",
          key: "2",
        },
        {
          label: "未通过",
          key: "3",
        },
      ],
      ipagination: {
        total: 0,
        pageSize: 10,
        current: 1,
        pageSizeOptions: ["10", "20", "30", "40", "50"],
        showTotal: (total) => `共有 ${total} 条数据`,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) =>
          this.onSizeChange(current, pageSize),
        onChange: (page, pageSize) => this.onPageChange(page, pageSize),
      },
      form: this.$form.createForm(this, { name: "coordinated" }),
      formLine: {},
      matchColumns: [
        {
          title: '企业名称',
          dataIndex: 'entName',
          scopedSlots: { customRender: 'entName' }
        }
      ],
      recommCompanyInfo: []
    };
  },
  created() {
    this.getEntBaseInfo();
    setTimeout(() => {
      this.GetproductList();
    }, 500);
  },
  methods: {
    // 查看推送
    seeReco(record) {
      let requestData = {
        demandNo: record.productNo === null ? '' : record.productNo
      }
      getProductEntPush(requestData).then(res => {
        if(res && res.code === 200) {
          const { data } = res
          this.recommCompanyInfo = data
          this.recoVis = true
        }else {
          this.$message.error('查看失败')
        }
      }).catch(err => {
        if(err) {
          this.$message.error('服务器错误')
        }
      })
    },
    // 关闭推荐弹框
    cancelRec() {
      this.recoVis = false
    },
    Renewal(item) {
      console.log(item.id);
      var that = this;
      this.$confirm({
        title: "您是否确认该产品内容准确无误并进行续期？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          // 点击确定
          that.addDurationTime(item.id);
        },
        onCancel() {
          // 点击取消
          console.log("Cancel");
        },
      });
    },
    // 续签
    addDurationTime(id) {
      let params = { id };
      addDurationTime(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("续期成功");
          this.GetproductList();
        }
      });
    },
    //获取企业基本信息
    getEntBaseInfo() {
      getEntBaseInfo().then((res) => {
        console.log("获取企业信息");
        console.log(res);
        if ((res.code = 200)) {
          this.userId = res.data.userId;
          this.isSign = res.data.isSign;
        }
      });
    },
    checkChange(e) {
      console.log(e.target.checked);
      this.checkNick = e.target.checked;
      if (e.target.checked == true) {
        this.productIslimited = 1;
      } else {
        this.productIslimited = null;
      }
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          // if (values.Data != undefined) {
          //   var updateTimeFrom = moment(values.Data[0]).format("YYYY-MM-DD");
          //   var updateTimeTo = moment(values.Data[1]).format("YYYY-MM-DD");
          // }
          let productIslimited = this.productIslimited;
          console.log(productIslimited);
          this.ipagination.current = 1;
          this.formLine = {
            keyword: values.keyword,
            productStatus: values.productStatus,
            auditStatus: values.auditStatus,
            messageCountFrom: values.messageCountFrom,
            messageCountTo: values.messageCountTo,
            priceFrom: values.priceFrom,
            priceTo: values.priceTo,
            productIslimited,
            // updateTimeFrom,
            // updateTimeTo
          };
          console.log(this.formLine);
          this.GetproductList();
        }
      });
    },
    clear() {
      this.updateTimeFrom = "";
      this.updateTimeTo = "";
      this.checkNick = false;
      // 清空表单
      this.form.resetFields();
      this.ipagination.current = 1;
      this.formLine = {};
      this.GetproductList();
    },
    handleChange(value) {
      console.log(`selected ${value}`);
    },
    onChange(date, dateString) {
      console.log(date, dateString);
      this.updateTimeFrom = dateString[0];
      this.updateTimeTo = dateString[1];
    },
    add() {
      this.$nextTick(() => {
        if (this.isSign == 1) {
          this.$router.push("/usercenter/ProductsRelease");
        } else {
          this.$store.commit('setIsSign',true);
          setIsSign(true);
          // this.$message.warning('您需要完成信用承诺函签署再进行该操作。')
        }
      });
    },
    seeEdit(record) {
      let id = record.id;
      this.$router.push({
        path: "/usercenter/ProductLook",
        query: { id },
      });
    },
    handleEdit(recode) {
      let id = recode.id;
      this.$router.push({
        path: "/usercenter/ProductEdit",
        query: { id },
      });
    },
    deleEdit(item) {
      var that = this;
      this.$confirm({
        title: "您确定要删除此信息吗?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          // 点击确定
          that.Deleteproduct(item.id);
        },
        onCancel() {
          // 点击取消
          console.log("Cancel");
        },
      });
    },
    updateProductStatus(id, productStatus, productName) {
      let _params = {
        id,
        productStatus,
        productName,
      };
      updateProductStatus(_params).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.GetproductList();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },
    //  上架
    showInformation(item) {
      console.log(item);
      var that = this;
      this.$confirm({
        title: "您确定要上架此商品吗?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          // 点击确定
          let id = item.id;
          let productStatus = 1;
          let productName = item.productName;
          that.updateProductStatus(item.id, productStatus, productName);
        },
        onCancel() {
          // 点击取消
          console.log("Cancel");
        },
      });
    },
    // 下架
    operation(item) {
      var that = this;
      this.$confirm({
        title: "您确定要下架此商品吗?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          // 点击确定
          let id = item.id;
          let productStatus = 2;
          let productName = item.productName;
          that.updateProductStatus(item.id, productStatus, productName);
        },
        onCancel() {
          // 点击取消
          console.log("Cancel");
        },
      });
    },
    //删除
    Deleteproduct(params) {
      Deleteproduct({ id: params }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("删除成功");
          if (this.ProduceList.length == 1) {
            // 如果只有最后一条就刷新上一页
            this.ipagination.current--;
          }
          if (this.ipagination.current < 1) {
            this.ipagination.current = 1;
          }

          this.GetproductList();
        } else {
          this.$message.warning("删除失败");
        }
      });
    },
    // 分页搜索
    onPageChange(page, pageSize) {
      this.ipagination.current = page;
      this.GetproductList();
    },
    // 页容量改变
    onSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize;
      this.ipagination.current = current;
      this.GetproductList();
    },
    // 获取供应产品列表
    GetproductList() {
      let _params = {
        size: this.ipagination.pageSize,
        current: this.ipagination.current,
        userId: this.userId,
        updateTimeFrom: this.updateTimeFrom,
        updateTimeTo: this.updateTimeTo,
        orderTypes: 7,
        ...this.formLine,
      };
      GetproductList(_params)
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            this.ProduceList = res.data.records;
            this.ipagination.total = res.data.total;
            this.ProduceList.forEach((item) => {
              item.ishandleEdit = true;
              item.isdeleEdit = true;
              item.isshowInformation = true;
              item.isoperation = true;

              if (item.auditStatus == 1) {
                //审核中
                item.ishandleEdit = false;
                item.isdeleEdit = false;
                item.isshowInformation = false;
                item.isoperation = false;
              } else if (item.auditStatus == 2) {
                // 已通过
                if (item.productStatus == 1) {
                  //已上架
                  item.isshowInformation = false;
                } else if (item.productStatus == 2) {
                  //未上架
                  item.isshowInformation = true;
                  item.isoperation = false;
                }
              } else if (item.auditStatus == 3) {
                // 未通过
                item.isshowInformation = false;
                item.isoperation = false;
              }
            });
          }
        })
        .catch((error) => {});
    },
  },
};
</script>

<style lang="less" scoped>
.MyNeed {
  padding: 17px 24px;
  background: #fff;
  .MyNeed-title {
    &:nth-child(1) {
      font-size: 22px;
      color: #303133;
    }
    .add-btn {
      margin-left: 16px;
      width: 60px;
      height: 32px;
      background-color: #ffffff;
      border-radius: 4px;
    }
  }

  .card-box {
    padding: 16px 19px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 24px;
  }

  .action {
    span {
      a {
        font-size: 14px;
        color: #188af1;
      }
    }
  }
  .operate-cls {
    display: grid;
    grid-template-columns: 75px 75px;
  }
}
.expire {
  background-color: red;
  color: #fff;
  border: 1px solid red;
}
</style>